/** 1. 类目新建 */
<template>
  <div class="cards_list">
    <a-card>
      <template #title>
        <h3 class="category_card_title">待对齐类目</h3>
      </template>
      <a-descriptions bordered>
        <a-descriptions-item label="类目编码">
          {{ step_data.hancode_category.category_code || '待选择' }}
        </a-descriptions-item>
        <a-descriptions-item label="类目名称">
          {{ step_data.hancode_category.category_name || '待选择' }}
        </a-descriptions-item>
        <a-descriptions-item label="类目导航">
          {{ step_data.hancode_category.category_path || '待选择' }}
        </a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card>
      <template #title>
        <h3 class="category_card_title">对齐类目</h3>
      </template>
      <template #extra>
        <a-space>
          <a-button type="primary" ghost @click="on_new_category"
            >新增对齐类目</a-button
          >
        </a-space>
      </template>

      <a-list
        :data-source="step_data.mapping_categories"
        :grid="{ gutter: 4, xs: 1, sm: 2, md: 3, lg: 4, xl: 4, xxl: 4 }"
      >
        <template #renderItem="{ item }">
          <a-list-item>
            <a-card hoverable class="card_item">
              <template #cover>
                <img
                  alt="site_logo"
                  class="site_logo"
                  :src="item.site_logo_url"
                />
              </template>
              <h3>{{ item.category_name }}</h3>
              <p>{{ item.nav_breadcrumb }}</p>
              <p>{{ item.category_code }}</p>
              <template #actions>
                <a-space direction="horizontal">
                  <!-- <a-button
                    :icon="h(PushpinOutlined)"
                    :disabled="!(first_start && can_set_baseline)"
                    @click="set_baseline(item)"
                    >设为基准</a-button
                  > -->
                  <a-button
                    :danger="true"
                    :icon="h(DeleteOutlined)"
                    @click="remove_category(item)"
                    :disabled="step_data.mapping_categories.length <= 1"
                    >删除类目</a-button
                  >
                </a-space>
              </template>
            </a-card>
          </a-list-item>
        </template>
      </a-list>
      <template #actions>
        <a-space>
          <a-button type="primary" @click="finish()" :disabled="!first_start"
            >提交保存</a-button
          >
          <!-- <a-button
            style="margin-left: 10px"
            @click="
              step_data.mapping_categories =
                step_data.mapping_categories.filter((item) => item.baseline)
            "
            >清空重选</a-button
          > -->
          <a-button
            style="margin-left: 10px"
            :danger="true"
            @click="reset_process"
            >重置流程</a-button
          >
        </a-space>
      </template>
    </a-card>
    <read-only-mask :enabled="step_data.read_only" />
  </div>
  <a-modal
    v-model:open="open_add_category_modal"
    title="新增对齐类目"
    :confirm-loading="confirm_loading"
    @ok="add_category"
    @cancel="reset_new_category_form"
  >
    <!-- 新建对齐类目的表单 -->
    <a-form
      :model="new_category_form"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 24 }"
    >
      <a-form-item label="选择站点">
        <a-select
          v-model:value="new_category_form.site_code"
          :options="all_site_options"
          @change="handle_site_change"
        />
      </a-form-item>
      <a-form-item label="选择类目">
        <a-select
          show-search
          :filter-option="filter_option"
          v-model:value="new_category_form.category_code"
          :options="all_category_options"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, h, onMounted, createVNode } from 'vue';
import { message, Modal } from 'ant-design-vue';
import {
  DeleteOutlined,
  ExclamationCircleOutlined,
  PushpinOutlined,
} from '@ant-design/icons-vue';
import {
  get_all_site_data,
  get_site_category_data,
  get_site_category_detail,
  fetch_all_site_scripts,
  clear_local_storage,
} from '@/utils/storage.js';
import { process_create } from '@/api/process.js';
import { storeToRefs } from 'pinia';
import { useCategoryStore } from '@/store/category';
import {
  get_process_step_data,
  fetch_process_data,
  fetch_condition_data,
  update_process_data,
  update_step_data,
} from '@/utils/selection';
import { useRouter } from 'vue-router';

const $router = useRouter();

const categoryStore = useCategoryStore();
const { selectedCategory } = storeToRefs(categoryStore);

const emit = defineEmits(['finish', 'update_pass_step']);

const open_add_category_modal = ref(false);
const confirm_loading = ref(false);

const process_data = ref(null);

const first_start = ref(true);
const can_set_baseline = ref(true);

const step_data = ref({
  // 是否只读
  read_only: false,

  // 新建标准类目表单
  hancode_category: {
    category_id: '',
    category_code: '',
    category_name: '',
    category_path: '',
  },

  // 对齐类目列表
  mapping_categories: [],
});

// 新建对齐类目表单
const new_category_form = ref({
  site_code: '',
  category_code: '',
});

const all_site_options = ref([]);
const all_category_options = ref([]);

// 新增对齐类目
const on_new_category = async () => {
  if (!first_start.value) {
    Modal.confirm({
      title: '检测到存在已对齐的类目数据冲突',
      icon: createVNode(ExclamationCircleOutlined),
      content: createVNode(
        'div',
        { style: 'color:red;' },
        '如果新增对齐类目，将清除所有相同组的已对齐类目数据并且无法撤回，是否继续？'
      ),
      async onOk() {
        all_site_options.value = await get_all_site_data();
        open_add_category_modal.value = true;
        first_start.value = true;
        emit('update_pass_step', 0);
      },
      onCancel() {
        console.log('Modal Canceled');
      },
      class: 'test',
    });
  } else {
    all_site_options.value = await get_all_site_data();
    open_add_category_modal.value = true;
  }
};

// 筛选类目项
const filter_option = (input, option) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// 选择站点变化
const handle_site_change = async () => {
  new_category_form.value.category_code = '';
  all_category_options.value = await get_site_category_data(
    new_category_form.value.site_code
  );
  // 将已经添加过的类目设置为禁用
  all_category_options.value = all_category_options.value.map(item => {
    if (
      step_data.value.mapping_categories.find(
        category_item =>
          category_item.category_code === item.value &&
          category_item.site_code === new_category_form.value.site_code
      )
    ) {
      item.disabled = true;
    }
    return item;
  });
};

// 重置添加类目表单
const reset_new_category_form = () => {
  new_category_form.value = {
    site_code: '',
    category_code: '',
  };
};

// 添加对齐类目
const add_category = async () => {
  console.log('new_category_form ->', new_category_form.value);
  console.log(`output->step_data.value`, step_data.value);
  confirm_loading.value = true;
  // 添加前检查
  if (
    !new_category_form.value.site_code ||
    !new_category_form.value.category_code
  ) {
    message.error('请选择站点和类目');
    confirm_loading.value = false;
    return;
  }
  if (
    step_data.value.mapping_categories.find(
      item =>
        item.baseline && item.site_code === new_category_form.value.site_code
    )
  ) {
    message.error('基准站点只能添加一个类目');
    confirm_loading.value = false;
    return;
  }
  if (
    step_data.value.mapping_categories.find(
      item =>
        item.category_code === new_category_form.value.category_code &&
        item.site_code === new_category_form.value.site_code
    )
  ) {
    message.error('该类目已经存在');
    confirm_loading.value = false;
    return;
  }

  // 获取站点类目详细信息
  const category_detail = await get_site_category_detail(
    new_category_form.value.site_code,
    new_category_form.value.category_code
  );

  console.log(`output->category_detail`, category_detail);

  // 添加对齐类目
  step_data.value.mapping_categories.push({
    baseline: false,
    site_logo_url: category_detail.site_logo_url,
    site_name: category_detail.website_name,
    site_code: category_detail.website_code,
    category_id: category_detail.id,
    category_url: category_detail.category_href,
    category_img_url: category_detail.category_img_url,
    category_name: category_detail.category_name,
    category_code: category_detail.category_code,
    category_path: category_detail.nav_breadcrumb,
  });

  // 更新流程数据
  if (process_data.value && process_data.value.length > 1) {
    await update_step_data('CONFLICT_SOLVE', process_data.value, null);
    message.success('删除对齐类目成功');
  }

  // 关闭对话框
  setTimeout(() => {
    confirm_loading.value = false;
    open_add_category_modal.value = false;
    reset_new_category_form();
  }, 200);
};

// 删除对齐类目
const remove_category = category_item => {
  // console.log("category_item ->", category_item);
  // 删除前检查
  if (category_item.baseline) {
    message.error('基准站点不能删除');
    return;
  }

  Modal.confirm({
    title: '即将清空对齐流程数据',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode(
      'div',
      { style: 'color:red;' },
      '如果删除该对齐类目，将清除本流程所有后续步骤的对齐的信息并且无法撤回，是否继续？'
    ),
    async onOk() {
      // 删除对齐类目
      step_data.value.mapping_categories =
        step_data.value.mapping_categories.filter(
          item =>
            item.category_code !== category_item.category_code ||
            item.site_code !== category_item.site_code
        );
      // 更新流程数据
      process_data.value =
        process_data.value?.filter(item => item.process === 'START') ?? [];
      await update_process_data(process_data.value);
      first_start.value = true;
      emit('update_pass_step', 0);
      message.success('删除对齐类目成功');
    },
    onCancel() {
      console.log('Modal Canceled');
    },
    class: 'test',
  });
};

// 设置基准站点
const set_baseline = category_item => {
  // console.log("category_item ->", category_item);
  // 设置前检查
  if (category_item.baseline) {
    message.error('该站点已经是基准站点');
    return;
  }

  // 设置基准站点
  step_data.value.mapping_categories.forEach(item => {
    if (item.baseline) {
      item.baseline = false;
    }
  });
  category_item.baseline = true;

  // 更新顺序 保证基准站点在第一位
  const index = step_data.value.mapping_categories.findIndex(
    item =>
      item.category_code === category_item.category_code &&
      item.site_code === category_item.site_code
  );
  if (index > -1) {
    step_data.value.mapping_categories.splice(index, 1);
    step_data.value.mapping_categories.unshift(category_item);
  }
};

// 初始化: 获取当前步骤数据
onMounted(async () => {
  // 清空本地缓存
  clear_local_storage();

  process_data.value = await fetch_process_data(true);
  if (!process_data.value) {
    message.info('未读取到处理中的流程数据，从新流程开始');
  }

  // 读取当前步骤数据
  const last_step_data =
    get_process_step_data(process_data.value, 'START')?.data ?? null;
  if (last_step_data) {
    step_data.value = last_step_data;
    if (process_data.value.length > 0) {
      first_start.value = false;
      can_set_baseline.value = false;
    }
    message.success('读取过程数据成功');

    // 计算已经完成的步骤数
    const pass_step_count = process_data.value.length;
    message.info(`读取到已经完成 ${pass_step_count} 个步骤`);
    // 更新已经完成的步骤数
    emit('update_pass_step', pass_step_count);
    return;
  }

  // 获取必要脚本数据
  message.info('正在获取必要脚本数据');
  fetch_all_site_scripts();

  console.log('selectedCategory.value =>', selectedCategory.value);
  try {
    step_data.value.hancode_category = {
      category_id: selectedCategory.value.id,
      category_name: selectedCategory.value.categoryName,
      category_code: selectedCategory.value.categoryCode,
      category_path: selectedCategory.value.categoryPath,
      parent_id: selectedCategory.value.parentId,
    };
  } catch (err) {
    setTimeout(() => {
      message.error('获取待对齐标准类目信息失败，将返回类目选择页面...');
      $router.push({ path: '/category' });
    }, 100);
  }
});

// 完成步骤: 更新提交当前步骤数据
const finish = async () => {
  // console.log(
  //   `output->JSON(process_data.value)`,
  //   JSON.stringify(process_data.value)
  // );
  // 检查是否设置基准站点
  if (
    !step_data.value.mapping_categories.find(item => item.baseline === true)
  ) {
    message.error('请设置一个基准站点');
    return;
  }
  // 检查基准站点是否有多个类目
  let baseline_name = step_data.value.mapping_categories.find(
    item => item.baseline === true
  ).site_name;
  if (
    step_data.value.mapping_categories.filter(
      item => item.site_name === baseline_name
    ).length > 1
  ) {
    message.error('基准站点不能有多个类目');
    return;
  }

  message.info('正在提交数据，请稍后...');
  // 获取站点类目的条件数据，一并存入备用
  const condition_map = {};
  for (const site_category of step_data.value.mapping_categories) {
    console.log(`output->site_category`, site_category);

    if (
      !condition_map[
        `${site_category.site_code}:${site_category.category_code}`
      ]
    ) {
      condition_map[
        `${site_category.site_code}:${site_category.category_code}`
      ] = await fetch_condition_data(
        site_category.site_code,
        site_category.category_id,
        site_category.category_code
      );
    }

    for (const category_data of condition_map[
      `${site_category.site_code}:${site_category.category_code}`
    ]) {
      // 设置站点名
      category_data.site_name = site_category.site_name;
      // 设置基准站点
      if (site_category.baseline) {
        category_data.baseline = true;
      }
      // 设置类目名
      category_data.category_name = site_category.category_name;
      // 设置类目编码
      category_data.category_code = site_category.category_code;
      // 设置类目路径
      category_data.category_path = site_category.category_path;
      // 设置类目图片
      category_data.category_img_url = site_category.category_img_url;
      // 设置类目链接
      category_data.category_url = site_category.category_url;
      // 设置站点logo
      category_data.site_logo_url = site_category.site_logo_url;
    }
  }

  // 锁定只读
  step_data.value.read_only = true;

  // 创建流程
  let res = await process_create(selectedCategory.value.id, step_data.value, {
    condition_map,
    baseline_site_code: step_data.value.mapping_categories.find(
      item => item.baseline === true
    ).site_code,
  });
  console.log(`output-> res`, res);
  emit('finish');
};

// 重置流程
const reset_process = async () => {
  Modal.confirm({
    title: '是否重置流程',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode(
      'div',
      { style: 'color:red;' },
      '如果重置流程，将清除本流程所有步骤的数据并且无法撤回，是否继续？'
    ),
    async onOk() {
      // 清空本地缓存
      clear_local_storage();
      fetch_all_site_scripts();
      // 重置步骤
      step_data.value.read_only = false;
      step_data.value.mapping_categories = [];
      // 重置已经完成的步骤数
      emit('update_pass_step', 0);
      // 重置流程数据
      process_data.value = [];
      // 重置是否第一次开始
      first_start.value = true;
      message.success('重置流程成功');
    },
    onCancel() {
      console.log('Modal Canceled');
    },
    class: 'test',
  });
};
</script>

<script>
import {
  Form,
  FormItem,
  Space,
  Button,
  Select,
  List,
  ListItem,
  Card,
  Descriptions,
  DescriptionsItem,
  Divider,
  BadgeRibbon,
  Modal,
} from 'ant-design-vue';
import ReadOnlyMask from '../commons/ReadOnlyMask.vue';
export default {
  name: 'SelNewCategoryPage',
  components: {
    AList: List,
    AListItem: ListItem,
    ACard: Card,
    ADescriptions: Descriptions,
    ADescriptionsItem: DescriptionsItem,
    ADivider: Divider,
    ABadgeRibbon: BadgeRibbon,
    AForm: Form,
    AFormItem: FormItem,
    AButton: Button,
    ASpace: Space,
    ASelect: Select,
    AModal: Modal,
  },
};
</script>

<style lang="scss" scoped>
.cards_list {
  position: relative;
  padding: 0px 100px;

  .site_logo {
    width: 100%;
    height: 128px;
    object-fit: contain;
  }
}

.category_card_title {
  text-align: left;
}
</style>
